<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/24
 * Time: 14:47
 */

namespace app\lib\Exception;

use Exception;
use think\exception\Handle;
use think\Request;
use think\Log;

class HandleException extends Handle
{
    private $message = '';
    private $code = 0;
    private $error_code = 0;
    public function render(Exception $e)
    {
        if($e instanceof BaseException) {
            $this->message = $e->message;
            $this->code = $e->code;
            $this->error_code = $e->error_code;

        }else{
            if(config('app_debug')) {
                return parent::render($e);
            }
            $this->message = '对不起，是我们搞错了！！o(╥﹏╥)o';
            $this->code = 520;
            $this->error_code = 500;
            $this->writeErrorLog($e);
        }

        $result = [
            'message' => $this->message,
            'error_code' => $this->error_code,
            'url' => (Request::instance())->url()
        ];

        return json($result,$this->code);
    }

    private function writeErrorLog(Exception $error)
    {
        Log::init([
            'type' => 'file',
            'level' => ['error'],
            'path' => LOG_PATH
        ]);

        Log::record($error,'error');
    }
}